package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.Admin;
import com.tanhua.model.vo.AdminVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //登入
    public Map login(String username, String password, String verificationCode, String uuid) {
        //获取redis验证码
        String code = redisTemplate.opsForValue().get("CODE:" + uuid);
        //对比
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)) {
            throw new BusinessException("验证码错误");
        }
        //正确删除
        redisTemplate.delete("CODE:" + uuid);
        //查询用户
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Admin admin = adminMapper.selectOne(wrapper);
        //密码加密 比对
        password = SecureUtil.md5(password);
        if (admin == null|| !admin.getPassword().equals(password)){
            throw new BusinessException("用户名或者密码错误");
        }
        //正确 生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id",admin.getId());
        String token = JwtUtils.getToken(tokenMap);
        //4、返回
        Map retMap = new HashMap();
        retMap.put("token",token);
        return retMap;

    }
    //获取用户信息
    public AdminVo profile() {
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        AdminVo vo = AdminVo.init(admin);
        return vo;
    }
}
